package com.jishuo.nontax.bfc.tlq;

import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.nontax.bfc.dao.MessageSysMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 消息SN缓存服务
 */
@Service
public class BackMessageService {
    private static long clearTime = 0; // 上次清理时间
    private static long maxTime = 20 * 60; // 保留时间，20分钟
    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private MessageSysMapper messageSysMapper;

    /**
     * 缓存 消息SN
     * @param sn
     */
    public void setMsg(String sn) {
        if (nonTaxConfig.TLQ_CheckBackMsg == 1) {
            // 内存
            BackMessageCache.setMsg(sn);
        } else if (nonTaxConfig.TLQ_CheckBackMsg == 3) {
            // redis
        } else {
            // 数据库
            long curTime = System.currentTimeMillis() / 1000;
            if (curTime - clearTime > maxTime) {
                // 清理过期数据
                if (clearTime == 0) clearTime = curTime - maxTime;
                this.messageSysMapper.clearMessageCache(clearTime);
                clearTime = curTime;
            }

            this.messageSysMapper.insertMessageCache(sn, curTime);
        }
    }

    /**
     * 从缓存中获取
     * @param sn
     * @return
     */
    public boolean getSn(String sn) {
        if (nonTaxConfig.TLQ_CheckBackMsg == 1) {
            // 内存
            return BackMessageCache.getMsg(sn) != null;
        } else if (nonTaxConfig.TLQ_CheckBackMsg == 3) {
            // redis
        } else {
            // 数据库
            return this.messageSysMapper.selectMessageCache(sn) != null;
        }
        return false;
    }
}
